<?php

defined('AUTH_SERVICE') or define('AUTH_SERVICE','twitter');

require_once '../server.php';
require_once 'twitter.php';

$twitter = new Twitter(TWITTER_KEY, TWITTER_SECRET);

$returnURL = AUTH_BASE_URL. '/twitter/connect.php';

$twitter->setTimeOut(3600);
// get a request token

// get tokens

$task = (isset($_REQUEST['task'])) ? $_REQUEST['task'] : 'AuthAuthorize';

switch ($task)
{
    case "AuthAuthorize" :
        //if ( empty($_SESSION['twitter']['oauth_token']))

        $response = $twitter -> oAuthAccessToken($_GET['oauth_token'], $_GET['oauth_verifier']);
        
        // authorize
        if (!isset($_GET['oauth_token']))
        {
            $response = $twitter -> oAuthRequestToken($returnURL);
            $twitter -> oAuthAuthorize();
        }
        else
        {
            $_SESSION['twitter']['oauth_token'] = $response['oauth_token'];
            $_SESSION['twitter']['oauth_token_secret'] = $response['oauth_token_secret'];
            $_SESSION['twitter']['user_id'] = $response['user_id'];
            $datatopost['task'] = 'profile';
            
            //echo $params;
            header('Location: ' . $returnURL . "?" . http_build_query($datatopost,null,'&'));
        }
        break;
    case 'profile':
        $oauth_token = $_SESSION['twitter']['oauth_token'];
        $oauth_verifier = $_SESSION['twitter']['oauth_token_secret'];
                
        $twitter -> setOAuthToken($oauth_token);
        $twitter -> setOAuthTokenSecret($oauth_verifier);
        
        $user_id = $_SESSION['twitter']['user_id'];
        
        $data = $twitter->usersShow(null, $user_id);
        
        $result= Mapper::fromTwitter($data);
        
        processCentralServiceResponseData($result);
        
        break;
    
    case "contacts" :
        $oauth_token = $_POST['oauth_tok3n'];
        $oauth_verifier = $_POST['oauth_token_secret'];
        $user_id = $_POST['user_id'];
        
        $datatopost = "returnConnnetions=";
        $twitter -> setOAuthToken($oauth_token);
        $twitter -> setOAuthTokenSecret($oauth_verifier);
        //$friends = $twitter->friendsIds(null,$user_id);
        $friends = $twitter -> followersIds(null, $user_id);
        //get friends info//
        $aContacts = array();
        if ($friends)
        {
            $aContacts = array();
            $iLoop = (int)(count($friends) / 99);
            $iBegin = 0;
            while ($iBegin <= $iLoop)
            {
                $aFriendList = array_slice($friends, $iBegin * 99, 99);
                $aContacts = array_merge($aContacts, $twitter -> usersLookup($aFriendList, $aParams));
                $iBegin++;
            }
        }
        $friends = $aContacts;
        //end
        $index = 0;
        $index = 0;
        foreach ($friends as $k => $fri)
        {
            try
            {
                $name = str_replace(',', '', $fri['name']);
                //$friend_user = $twitter->usersShow($fri);
                $datatopost .= 'id_' . $index . ',' . $fri['id'] . ',name_' . $index . ',' . $name . ',pic_' . $index . ',' . $fri['profile_image_url'] . ',';
            }
            catch(Exception $e)
            {
                //$datatopost .=
                // 'id_'.$index.','.$fri['id'].',name_'.$index.','.'unknown'.',pic_'.$index.','.''.',';
                //continue;
            }
            //$datatopost[(string)$con->id] =
            // array('id'=>(string)$con->id,'name'=>(string)$con->{'first-name'},'pic'=>(string)$con->{'picture-url'});

            //$datatopost["name_".$index] = (string)$con->{'first-name'};
            //$datatopost["pic_".$index] = (string)$con->{'picture-url'};
            $index++;

        }
        $datatopost = str_replace(",,pic_", ",pic_", $datatopost);
        echo($datatopost);
        die();
        break;
    case "send_message" :
        $oauth_token = $_POST['oauth_tok3n'];
        $oauth_verifier = $_POST['oauth_token_secret'];
        $user_id = $_POST['user_id'];
        $log -> lwrite('send_message');
        $log -> lwrite($_POST);
        $log -> lwrite('oauth_token' . $oauth_token);
        $log -> lwrite('oauth_verifier' . $oauth_verifier);
        $log -> lwrite('user_id' . $user_id);
        $log -> lwrite('message' . $_POST['message_body']);
        $log -> lwrite('---------------');
        $connections = array();
        $twitter -> setOAuthToken($oauth_token);
        $twitter -> setOAuthTokenSecret($oauth_verifier);
        // connection messaging
        for ($i = 0; $i < 10000; $i++)
            if (isset($_POST[$i]))
                $connections[] = $_POST[$i];
        $log -> lwrite(print_r($connections, true));
        if (count($connections))
        {
            foreach ($connections as $con)
                try
                {
                    //$_POST['message_subject'], $_POST['message_body']
                    $reply = $twitter -> directMessagesNew($_POST['message_body'], null, $con);
                    $log -> lwrite(print_r($reply, true));
                }
                catch (Exception $e)
                {
                    $log -> lwrite($e -> getMessage());
                }

        }
        break;
}
